import axios from 'axios'

export let host: string
export let port: number

if (import.meta.env.MODE == 'production') {
	host = '/'
} else {
	host = 'http://127.0.0.1:4433/'
}

// 请求头
export const contentType = [
	'application/json; charset=UTF-8',
	'application/x-www-form-urlencoded; charset=UTF-8',
	'multipart/form-data; charset=UTF-8',
]

const requestBaseURL = 'api'
// 创建 axios 请求实例
const Axios = axios.create({
	baseURL: host + requestBaseURL,
	timeout: 3000, // 请求 2s 超时
	withCredentials: false, // 跨域请求是否需要携带 cookie
})

// 全局 http request 拦截
Axios.interceptors.request.use(
	(config) => {
		const token = localStorage.getItem('token')
		if (token && config.headers) config.headers.Authorization = token
		return config
	},
	(err) => {
		return Promise.reject(err.response)
	},
)

// 全局 http response 拦截
Axios.interceptors.response.use(
	(res) => {
		const data = res.data
		if (data.Code == 0) {
			return data
		} else {
			return Promise.reject(data)
		}
	},
	(err) => {
		return Promise.reject(err)
	},
)

export function Get(url: string, params: any, content = 0, timeout = Axios.defaults.timeout) {
	return Axios.get(url, {
		params,
		headers: { 'Content-Type': contentType[content] },
		timeout: timeout,
	})
}

export function Post(url: string, data: any, content = 0, timeout = Axios.defaults.timeout) {
	return Axios.post(url, data, {
		headers: { 'Content-Type': contentType[content] },
		timeout: timeout,
	})
}

export function Del(url: string, data: any, content = 0, timeout = Axios.defaults.timeout) {
	return Axios.delete(url, {
		data,
		headers: { 'Content-Type': contentType[content] },
		timeout: timeout,
	})
}

export function Put(url: string, data: any, content = 0, timeout = Axios.defaults.timeout) {
	return Axios.put(url, data, {
		headers: { 'Content-Type': contentType[content] },
		timeout: timeout,
	})
}

export default Axios
